package com.example.demo.slidingwindow;

import com.example.demo.leakybucket.RequireLeaky;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Aspect
@Component
@Slf4j
public class SlidingWindowAspect {
    @Resource
    SlidingWindowQueueService slidingWindowQueueService;

    @Around("@annotation(requireLeaky)")
    public void beforeAsyncQueuedMethod(ProceedingJoinPoint joinPoint, RequireLeaky requireLeaky) {
        // 将方法包装成Runnable放入队列
        Runnable task = () -> {
            try {
                joinPoint.proceed();
                slidingWindowQueueService.setCount(new AtomicInteger(slidingWindowQueueService.getCount().incrementAndGet()));
            } catch (Throwable e) {
                log.info(e.getMessage());
            }
        };
        boolean offer = slidingWindowQueueService.getQueue().offer(task);
        if (offer) {
            log.info("offer Queue");
        } else {
            log.info("Queue is full");
        }
    }
}